package cn.supermarket.controller.system;

import cn.supermarket.common.annotation.Log;
import cn.supermarket.common.config.ProjectConfig;
import cn.supermarket.common.core.controller.BaseController;
import cn.supermarket.common.core.entity.LoginUser;
import cn.supermarket.common.core.entity.Result;
import cn.supermarket.common.entity.system.SysUser;
import cn.supermarket.common.enums.BusinessType;
import cn.supermarket.common.utils.SecurityUtils;
import cn.supermarket.common.utils.StringUtils;
import cn.supermarket.common.utils.file.FileUploadUtils;
import cn.supermarket.common.utils.file.MimeTypeUtils;
import cn.supermarket.framework.web.service.TokenService;
import cn.supermarket.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 个人信息 业务处理
 * @Author yp
 * @Date 2024/5/27:13:52
 */
@RestController
@Api(value = "个人信息", tags = "个人信息")
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    @ApiOperation("个人信息")
    public Result profile()
    {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        Result result = Result.success(user);
        result.put("roleGroup", sysUserService.selectUserRoleGroup(loginUser.getUsername()));
        result.put("postGroup", sysUserService.selectUserPostGroup(loginUser.getUsername()));
        return result;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result updateProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhoneNumber(user.getPhoneNumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhoneNumber()) && !sysUserService.checkPhoneUnique(currentUser))
        {
            return error("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(currentUser))
        {
            return error("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (sysUserService.updateUserProfile(currentUser) > 0)
        {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (sysUserService.resetUserPwd(userName, newPassword) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    @ApiOperation(value = "上传头像", notes = "上传头像")
    public Result avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(ProjectConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (sysUserService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                Result ajax = Result.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
